<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
        v-model="editUser.currentValue"
        :name="editUser.editKey"
        :label="editUser.editName"
        :placeholder="`请填写${editUser.editName}`"
      />
    </van-cell-group>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        修改
      </van-button>
    </div>
  </van-form>
</template>


<script setup>
import { useRoute,useRouter } from 'vue-router';
import {onMounted, ref} from 'vue';
import myAxios from "../plugins/MyAxios.ts";
import {showToast} from "vant";
import {getCurrentUser} from "../service/user.ts";

const router = useRouter();
const route = useRoute();
console.log(route.query)
const editUser = ref({
  editKey: route.query.editKey,             // 要更新的列名给后端
  currentValue: route.query.currentValue,   // 要更新的值给后端
  editName: route.query.editName           // 前端传递过来的更新列名
})

// 编辑页面只是登录成功了才能进来的


// []这个语法就是动态取值，就不用像 "name" : song 这样写死name了
const onSubmit = async () => {
  const currentUser = await getCurrentUser()
  if (editUser.value.currentValue.length === 0) {
    showToast("修改值不能为空")
  } else if(!currentUser) {
    showToast("用户未登录")
  } else {
    const res = await myAxios.post('/user/update', {
      // editKey，currentValue，editName提交到后台
      "id": currentUser.id,
      [editUser.value.editKey]: editUser.value.currentValue,
    })
    console.log(res, '更新请求');
    if (res.code === 0 && res.data > 0) {
      showToast('修改成功');
      router.back();
    } else {
      showToast('修改错误');
    }
  }

};

</script>

<style scoped>

</style>